<?php


namespace app\api\controller;


use app\common\controller\Api;
use app\common\controller\Util;
use think\Db;
use think\Env;
use think\Exception;
use think\Hook;


class Bizquestion extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /** 题库详情
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function questionBankInfo()
    {

        $id = $this->request->request('id');
        if ($id) {
            $List = Db::name("question_bank")->alias('qb')
                //课程
                ->join('by_course byc', 'qb.course_id =byc.id ', 'LEFT')
                // 章节
//            年级
                ->join('by_grade bg', 'qb.grade_id = bg.id', 'LEFT')
                ->join('by_subject bs', 'qb.subject_id = bs.id', 'LEFT')
                ->where('qb.id', $id)
                ->field('qb.* ,byc.title,bg.grade_name,bs.subject_name')
                ->order("qb.id desc")->select();
            $this->success("ok", $List);
        }
        $this->error("ok", '参数id不存在');
    }

    /** 题目详情
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function questionInfo()
    {

        $id = $this->request->request('id');
        if ($id) {

            $detail = Db::name("question")->alias('byq')
                //课程
                ->join('by_question_bank bqb', 'byq.bank_id =bqb.id ', 'LEFT')
                ->field('byq.type,byq.score,byq.q_info,byq.difficulty,byq.answer,byq.comm,byq.q_status,
                bqb.name')
                ->where('byq.id', $id)
                ->find();
            $items = Db::name('question_item')->where('question_id', $id)->select();
            $detail['items'] = $items;
            $this->success("ok", $detail);
        }
        $this->error("ok", '参数id不存在');
    }

    /**
     * @Notes:
     * @Author: zhao
     * @Date: 2020/9/1
     * @Time: 15:49
     * @Interface getQuestionBank
     * @param $user_id
     * @param $course_id
     * @param $grade_id
     * @param $subject_id
     * @return array
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     *  条件查询 题库
     */
    private function getQuestionBank($user_id, $course_id, $grade_id, $subject_id)
    {
        $myWhere['q_user.student'] = $user_id;
        if ($course_id) {
            $myWhere['byc.id'] = $course_id;
        }
        if ($grade_id) {
            $myWhere['bg.id'] = $grade_id;
        }
        if ($subject_id) {
            $myWhere['bs.id'] = $subject_id;
        }
        if ($user_id) {

            $total = Db::name("question_bank_user")->alias('q_user')
                //课程
                ->join('question_bank qb', 'qb.id =q_user.bank ', 'LEFT')
                ->join('by_course byc', 'qb.course_id =byc.id ', 'LEFT')
                // 章节
                ->join('by_grade bg', 'qb.grade_id = bg.id', 'LEFT')
                ->join('by_subject bs', 'qb.subject_id = bs.id', 'LEFT')
                ->where($myWhere)
                ->field(' q_user.*,qb.name ,byc.title,bg.grade_name,bs.subject_name')
                ->order("q_user.id desc")
                ->count();


            $list = Db::name("question_bank_user")->alias('q_user')
                //课程
                ->join('question_bank qb', 'qb.id =q_user.bank ', 'LEFT')
                ->join('by_course byc', 'qb.course_id =byc.id ', 'LEFT')
                ->join('by_grade bg', 'qb.grade_id = bg.id', 'LEFT')
                ->join('by_subject bs', 'qb.subject_id = bs.id', 'LEFT')
                ->where($myWhere)
                ->field(' q_user.*,qb.name ,byc.title,bg.grade_name,bs.subject_name')
                ->order("q_user.id desc")
                ->select();
            return array("total" => $total, "rows" => $list);

        }
        return array();
    }

    /**
     * @Notes:
     * @Author: zhao
     * @Date: 2020/9/1
     * @Time: 16:27
     * @Interface questionList
     * @param $student_id
     * @param $bank_id
     * @param $type
     * @param $difficulty
     * @param $q_type
     * @return array
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 查询题目列表
     */
    private function questionList($student_id, $course_id, $type, $difficulty, $lesson_id)
    {

        $myWhere['q_user.student'] = $student_id;
        if (Util::checkEmpty($course_id)) {
            $myWhere['bqb.course_id'] = $course_id;
        }
        if (Util::checkEmpty($type)) {
            $myWhere['q_user.type'] = $type;
        }
        if (Util::checkEmpty($difficulty)) {
            $myWhere['byq.difficulty'] = $difficulty;
        }
        if (Util::checkEmpty($lesson_id)) {
            $myWhere['bqb.lesson_id'] = $lesson_id;
        }
        $total = Db::name("question_user")->alias('q_user')
            ->join("question byq", 'q_user.question=byq.id')
            //课程
            ->join('by_question_bank bqb', 'byq.bank_id =bqb.id ', 'LEFT')
            ->field('q_user.my_answer,q_user.type,q_user.my_score,q_user.create_time,
                byq.type q_type,byq.score,byq.q_info,byq.difficulty,byq.answer,byq.comm,byq.q_status,
                bqb.name')
            ->where($myWhere)
            ->order("q_user.id desc")
            ->count();
        $list = Db::name("question_user")->alias('q_user')
            ->join("question byq", 'q_user.question=byq.id')
            //课程
            ->join('by_question_bank bqb', 'byq.bank_id =bqb.id ', 'LEFT')
            ->field('byq.id,q_user.question,q_user.my_answer,q_user.type,q_user.my_score,q_user.create_time,
                        byq.type q_type,byq.score,byq.q_info,byq.difficulty,byq.answer,byq.comm,byq.q_status,
                bqb.name')
            ->where($myWhere)
            ->order("q_user.id desc")
            ->select();
        if ($list) {
            foreach ($list as $key => &$value) {
                $questionId = $value['question'];
                $items = Db::name('question_item')->where('question_id', $questionId)->column('q_detail', 'q_a');
                $value['items'] = $items;
            }
        }
        $result = array("total" => $total, "rows" => $list);
        return $result;
    }

    /**
     * 我的题库列表
     */
    public function myQuestionBanks()
    {

        $user_id = $this->auth->id;
        if ($user_id) {
            $student = Db::name('student')->where('user_id', $user_id)->find();

            $course_id = $this->request->request('course_id');
            $grade_id = $this->request->request('grade_id');
            $subject_id = $this->request->request('subject_id');
            $type = $this->request->request('type');
            $difficulty = $this->request->request('difficulty');
            $q_type = $this->request->request('q_type');
            if ($student) {
                $result = $this->getQuestionBank($student['id'], $course_id, $grade_id, $subject_id)['rows'];
                $result2 = array();
                foreach ($result as $key => &$value) {
                    $arr = $this->questionList($student['id'], $value['bank'], $type, $difficulty, $q_type)['rows'];
                    array_push($result2, $arr);
                }
                $this->success("row", $result2);
            }
        }
    }

    /**
     * 我的题目列表
     */
    public function myQuestion()
    {
        $type = input('type');
        if($type == 'error'){
            $this->myQuestions();
        }
        $user_id = $this->auth->id;
        $student = Db::name('student')->where('user_id', $user_id)->find();
        if ($student) {
//            拼查询条件
            $course_id = $this->request->request('course_id');
            $bank_id = $this->request->request('bank_id');
            $difficulty = $this->request->request('difficulty');
            $lesson_id = $this->request->request('lesson_id');
            if (Util::checkEmpty($course_id)) {
                $myWhere['bqb.course_id'] = $course_id;
            }
            if (Util::checkEmpty($lesson_id)) {
                $myWhere['bqb.lesson_id'] = $lesson_id;
            }
            $total = Db::name("question")->alias('byq')
                ->join('by_question_bank bqb', 'byq.bank_id =bqb.id ', 'LEFT')
                ->field('byq.id,byq.type q_type,byq.score,byq.q_info,byq.difficulty,byq.answer,byq.comm,byq.q_status,
                bqb.name')
                ->where($myWhere)
                ->count();
            $list = Db::name("question")->alias('byq')
                ->join('by_question_bank bqb', 'byq.bank_id =bqb.id ', 'LEFT')
                ->field('byq.id,byq.type q_type,byq.score,byq.q_info,byq.difficulty,byq.answer,byq.comm,byq.q_status,
                bqb.name')
                ->where($myWhere)
                ->select();
            if ($list) {
                foreach ($list as $key => &$value) {
                    $questionId = $value['id'];
                    $items = Db::name('question_item')->where('question_id', $questionId)->column('q_detail', 'q_a');
                    $value['items'] = $items;
                }
            }
            $result = array("total" => $total, "rows" => $list);
            $this->success("row", $result);
        }
    }

    /**
     * 我的题目列表
     */
    public function myQuestions()
    {
        $user_id = $this->auth->id;
        $student = Db::name('student')->where('user_id', $user_id)->find();
        if ($student) {
//            拼查询条件
            $myWhere['q_user.student'] = $student['id'];
            $course_id = $this->request->request('course_id');
            $type = $this->request->request('type ');
            $difficulty = $this->request->request('difficulty');
            $lesson_id = $this->request->request('lesson_id');
            $result = $this->questionList($student['id'], $course_id, $type, $difficulty, $lesson_id);
            $this->success("row", $result);
        }
    }

    /**
     * 答题
     */
    public function answerQuestion()
    {
        $res = file_get_contents("php://input");
        $json_array = Util::isJson(htmlspecialchars_decode($res), true);
        $user_id = $this->auth->id;
        $student = Db::name('student')->where('user_id', $user_id)->find();
        if (!$student) {
            return $this->error('用户不存在');
        }
        $json_array = $json_array['json'];
        foreach ($json_array as $key => &$value) {
            $q = $value['question'];
            $a = $value['my_answer'];
            $this->doAnswer($q, $a, $student['id']);
        }

        return $this->success('操作成功');
    }


    private function doAnswer($q, $a, $student_id)
    {
        Db::startTrans();
        try {
//                判断是否已经答过
            $myAnswer = Db::name('question_user')
                ->where('student', $student_id)
                ->where('question', $q)
                ->find();
            if ($myAnswer) {
                throw new Exception('请不要重复答');
            }
//                插入题库标识
            $question = Db::name('question')->where('id', $q)->find();
//                todo 待优化 ，回答和问题的答案对比是否相同
            $param['type'] = 'normal';
            $param['comm'] = 'comm ...';
            if ($question['answer'] !== $a) {
                $param['type'] = 'error';
                $param['my_score'] = 0;
            } else {
                $param['my_score'] = $question['score'];
            }
            $param['my_answer'] = $a;
            $param['question'] = $q;
            $param['question_bank'] = $question['bank_id'];
            $param['create_time'] = date("Y-m-d H:i:s");
            $param['student'] = $student_id;
            $res = Db::name('question_bank_user')->where(['student' => $student_id,'bank' => $question['bank_id']])->find();
            Db::name('question_user')->insert($param);
            if(!empty($res)){
                Db::name('question_bank_user')->where('id',$res['id'])->setInc('myscore',$param['my_score']);
                Db::name('question_bank_user')->where('id',$res['id'])->update(['create_time' => date("Y-m-d H:i:s")]);
            }else{
                Db::name('question_bank_user')->insert(['student' => $student_id, 'bank' => $question['bank_id'],'myscore' => $param['my_score'],'create_time' => date("y-m-d H:i:s")]);
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }

}